import {h, createApp} from "vue"
import AppDropdownMenu from "@/components/AppDropdownMenu.vue";

/**
 * 创建元素菜单
 */
function createMenu(el: any, event: PointerEvent, binding: any) {
    //创建遮罩
    el.menuContainer = document.createElement('div');
    el.menuContainer.style.width = `${window.innerWidth}px`
    el.menuContainer.style.height = `${window.innerHeight}px`
    el.menuContainer.style.position = 'fixed'
    el.menuContainer.style.left = '0px'
    el.menuContainer.style.zIndex = '99999'
    el.menuContainer.style.top = '0px'
    el.menuContainer.oncontextmenu = function (e: any) {
        el.menuContainer.remove()
        e.preventDefault()
    }
    el.menuContainer.onclick = function (e: any) {
        el.menuContainer.remove()
        e.preventDefault()
    }
    document.body.appendChild(el.menuContainer)
    createApp(h(AppDropdownMenu, {
        top: `${event.clientY}px`,
        left: `${event.clientX}px`,
        onTrigger(key: string, param: any) {
            if (typeof binding.arg === 'function') {
                binding.arg(key, param)
            }
        },
        menu: (typeof binding.value === 'function') ? binding.value() : binding.value
    })).mount(el.menuContainer)

    event.preventDefault();
}


/**
 * 复制指令
 */
const menu: { name: string, directive: any } = {
    name: 'menu',
    directive: {
        beforeMount(el: any, binding: any) {
            el.addEventListener('contextmenu', function (event: PointerEvent) {
                createMenu(el, event, binding)
            })
        },
        beforeUnmount(el: any) {
            el?.menuContainer?.remove()
        }
    }
}

/**
 * 复制指令
 */
export default menu